<template>
  <view class="">
    <uni-indexed-list :options="list" :show-select="false" @click="bindClick" />
  </view>
</template>

<script>
export default {
  data() {
    return {
      list: [], //城市列表索引
      cityinfo: [], //城市列表
    };
  },
  methods: {
    async getcitylist() {
      let res = await this.$api.getCityList(); //获取城市列表
      let hotres = await this.$api.getHotCity(); //获取热门城市列表
      console.log(hotres);
      hotres = hotres.data.msg;
      //热门城市排序
      let hotobj = hotres.reduce(
        (pre, cut, index) => {
          pre.data.push(cut.name);
          return pre;
        },
        {
          letter: "热",
          data: [],
        }
      );
      console.log(hotobj);
      console.log(res);
      //城市排序
      let citys = res.data.msg;
      this.cityinfo = citys; //组合城市 获取code
      let arr = citys.reduce((pre, cut, index) => {
        let t = pre.some((v) => {
          if (v.letter == cut.short) {
            //如果首字母相同
            v.data.push(cut.name);
          }
          return v.letter == cut.short;
        });

        //首字母不同
        if (!t) {
          pre.push({
            letter: cut.short,
            data: [cut.name],
          });
        }
        return pre;
      }, []);
      console.log(arr);
      //字母排序
      // console.log("c".charCodeAt());
      arr.sort((a, b) => a.letter.charCodeAt() - b.letter.charCodeAt());
      arr.unshift(hotobj); //热门城市排前面
      let cutcity = {
        letter: "#",
        data: [uni.getStorageSync("cityinfo").name],
      };
      arr.unshift(cutcity); //热门城市排最前面
      this.list = arr;
    },

    bindClick(e) {
      // console.log(e);
      //找当前城市
      let selcity = this.cityinfo.find((v) => v.name == e.item.name);
      //本地存储
      uni.setStorageSync("cityinfo", selcity);
      uni.$emit("selcity");
      uni.navigateBack();
    },
  },
  mounted() {
    this.getcitylist();
  },
};
</script>

<style>
</style>